#pragma once
#include<iostream>
#include"protocol.hpp"

enum{
    Div_Zero = 1,
    Mod_zero,
    Other_Oper
};

class ServerCal{
public:
    ServerCal(){}

    ~ServerCal(){}
    
    Response CalculatorHelper(const Request &req){
        Response resp(0,0);// 
        switch (req.op)
        {
            case '+':
                resp.result = req.x + req.y;
                break;
            case '-':
                resp.result = req.x - req.y;
                break;
            case '*':
                resp.result = req.x * req.y;
                break;
            case '/':
                if(req.y==0){
                    resp.code = Div_Zero;
                }else{
                    resp.result = req.x/req.y;
                }
                break;
            case '%':
                if(req.y == 0)
                    resp.code = Mod_zero;
                else 
                    resp.result = req.x%req.y;
                break;
            default:
                resp.code = Other_Oper;
                break;
        }
        return resp;
    }

    std::string Calculator(std::string &package){
        std::string content;
        bool r = Decode(package, &content); // 解码提取一个序列化
        if(!r){
            return "";
        }
        // std::cout<<"content:"<<content<<std::endl;
        Request req;
        r = req.Deserialize(content); // 解序列化
        if(!r) return "";

        content = "";
        Response resp = CalculatorHelper(req);//calculate and response
        
        resp.Serialize(&content); //序列化
        // std::cout<<"content:"<<content<<std::endl;
        content = Encode(content);//编码序列化
        
        return content;
    }
};
